import { PropsWithChildren, useMemo, useState } from "react";
import { SvgIcon } from "./SvgIcon";
import { Button, Dropdown, Input, MenuProps, message, Space } from "antd";
import { DownOutlined, SearchOutlined } from "@ant-design/icons";
import { ILegalAdviceItem } from "../store";
import { SiderBarItem } from "./SiderBarItem";
import { RequestRender } from "./RequestRender";
import {
  fetchRecommendQuestion,
  fetchUpdateChatHistory,
} from "@/api/server/recommend_question";
import { Condition } from "./Condition";

type TType = "text-read" | "legal-search" | "legal-advice" | "doc-generation";

interface ISiderBarProps {
  className?: string;
  activeKey?: string;
  listType?: string;
  collapse?: boolean;
  list?: ILegalAdviceItem[];
  onSetActiveKey?: (k: string) => void;
  onSetCollapse?: (k: boolean) => void;
  setListType?: (k: string) => void;
  refreshList?: () => void;
  listSearch?: string;
  setListSearch?: (k: string) => void;
  type: TType;
}

export function SiderBar(props: PropsWithChildren<ISiderBarProps>) {
  const {
    list,
    onSetActiveKey,
    activeKey,
    onSetCollapse,
    collapse,
    type: barType,
    listSearch,
    setListSearch,
    listType,
    setListType,
    refreshList,
  } = props;
  const [showSearch, setShowSearch] = useState(false);

  const items = useMemo(() => {
    const historyLable =
      barType === "doc-generation"
        ? "历史生成"
        : barType === "text-read"
        ? "历史阅读"
        : "历史对话";
    const favoriteLable =
      barType === "doc-generation"
        ? "收藏文书"
        : barType === "text-read"
        ? "收藏阅读"
        : "收藏对话";
    return [
      {
        label: historyLable,
        key: "history",
        onClick: (e: { key: string }) => setListType(e.key),
      },
      {
        label: favoriteLable,
        key: "favorites",
        onClick: (e: { key: string }) => setListType(e.key),
      },
    ];
  }, [barType, setListType]);

  const typeLabel = useMemo(() => {
    const info = items.find((item) => item?.key === listType);
    return info?.label;
  }, [listType, items]);

  const onClickNewTask = () => {
    onSetActiveKey?.("");
  };

  const dropdownItems: MenuProps["items"] = [
    {
      label: (
        <div className="flex flex-row items-center min-w-[120px] gap-[6px]">
          <SvgIcon name="icon-bianji_default" />
          <div>编辑</div>
        </div>
      ),
      key: "edit",
    },
    {
      label: (
        <div className="flex flex-row items-center min-w-[120px] gap-[6px]">
          <SvgIcon name="icon-zhiding_default" />
          <div>置顶</div>
        </div>
      ),
      key: "top",
    },
    {
      label: (
        <div className="flex flex-row items-center min-w-[120px] gap-[6px]">
          <SvgIcon name="icon-shoucang_default" />
          <div>收藏</div>
        </div>
      ),
      key: "favorite",
    },
    {
      label: (
        <div className="flex flex-row items-center min-w-[120px] gap-[6px]">
          <SvgIcon name="icon-shanchu_default" />
          <div>删除</div>
        </div>
      ),
      key: "delete",
    },
  ];

  const filterList = list;
  // list
  //   ?.filter((item) => {
  //     if (listType === "favorites") {
  //       return item.is_favorite;
  //     }
  //     return true;
  //   })
  //   ?.filter((item) => {
  //     if (listSearch?.trim()) {
  //       return item.name.indexOf(listSearch) >= 0;
  //     }
  //     return true;
  //   }) || [];

  return (
    <>
      <div
        className="SideBar"
        style={{
          width: collapse ? 0 : 274,
          transform: collapse ? "translate(-100%)" : undefined,
        }}
      >
        <div
          className="pt-[20px] pb-[16px] px-[16px] flex flex-col gap-[16px] h-full
      "
        >
          <Button onClick={onClickNewTask} type="primary" size="large">
            新建任务
          </Button>
          <div className="flex flex-row justify-between items-center">
            <Condition condition={showSearch}>
              <Input
                autoFocus
                allowClear
                prefix={<SearchOutlined />}
                defaultValue={listSearch}
                onBlur={(e) => {
                  const v = e.target.value?.trim();
                  setListSearch(v);
                  if (!v) {
                    setShowSearch(false);
                  }
                }}
                onKeyDown={(e: any) => {
                  if (e?.code === "Enter") {
                    e.target?.blur();
                  }
                }}
              />
            </Condition>
            <Condition condition={!showSearch}>
              <Dropdown menu={{ items }} trigger={["click"]}>
                <a onClick={(e) => e.preventDefault()}>
                  <Space>
                    {typeLabel}
                    <DownOutlined />
                  </Space>
                </a>
              </Dropdown>
              <div
                className="cursor-pointer"
                onClick={() => {
                  setShowSearch(true);
                }}
              >
                <SearchOutlined />
              </div>
            </Condition>
          </div>
          <div className="flex flex-col flex-1 min-h-0 gap-[16px] overflow-auto">
            {filterList?.map((item) => {
              const isActive = item.key === activeKey;
              return (
                <SiderBarItem
                  key={item.key}
                  isActive={isActive}
                  onClick={() => onSetActiveKey?.(item.key)}
                  onOperation={(type, value) => {
                    let p;
                    if (type === "pinned") {
                      p = {
                        chat_id: item.key,
                        isPinned: value,
                        message: value ? "置顶成功" : "取消置顶成功",
                      };
                    } else if (type === "favorite") {
                      p = {
                        chat_id: item.key,
                        isFavorite: value,
                        message: value ? "收藏成功" : "取消收藏成功",
                      };
                    } else if (type === "delete") {
                      p = {
                        chat_id: item.key,
                        isDeleted: value,
                        message: "删除成功",
                      };
                    } else if (type === "edit") {
                      p = {
                        chat_id: item.key,
                        title: value,
                        message: "修改成功",
                      };
                    }

                    if (p) {
                      fetchUpdateChatHistory(p).then((res) => {
                        message.success(p.message);
                        refreshList?.();
                      });
                    }
                  }}
                  info={item}
                />
              );
            })}

            <Condition condition={barType === "text-read"}>
              <div className="mt-[24px]">
                <div className="flex flex-row items-center justify-between textReadItem cursor-pointer">
                  <div className="flex flex-row items-center gap-[4px]">
                    <div>
                      <DownOutlined className="text-[12px]" />
                      {/* <RightOutlined className="text-[12px]" /> */}
                    </div>
                    <img src="/images/folder.svg" />
                    <div className="text-[14px] font-[500]">未命名任务01</div>
                  </div>
                  <Dropdown menu={{ items: dropdownItems }} trigger={["click"]}>
                    <div className="w-[24px] h-[24px] rounded-[4px] flex flex-row items-center justify-center hover:bg-[#8793ab1f] cursor-pointer textReadMore">
                      <img src="/images/dot.svg" />
                    </div>
                  </Dropdown>
                </div>
                <div className="flex flex-col mt-[12px]">
                  <div className="hover:bg-[#F2F7FF] py-[12px] pl-[39px] pr-[12px] cursor-pointer rounded-[8px] textReadItem">
                    <div className="flex flex-row items-center gap-[8px]">
                      <SvgIcon
                        name="icon-a-conversation11"
                        color="rgb(44, 121, 241)"
                        size={16}
                      />
                      <div className="flex-1 min-w-0 text-[14px] font-[500] whitespace-nowrap text-ellipsis overflow-hidden">
                        2877d3d39d7aa296c1daab6c67e24f66.png
                      </div>
                      <div className="flex flex-row items-center gap-[8px] textReadMore">
                        <SvgIcon name="icon-bianji_default" />
                        <SvgIcon name="icon-shanchu_default" />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </Condition>
            <Condition condition={!(filterList?.length > 0)}>
              <div className="flex-1 min-h-0 flex flex-col items-center justify-center">
                <img className="w-[100px]" src="/images/empty.png" />
                <div className="text-[#878aab] text-[12px]">暂无数据</div>
              </div>
            </Condition>
          </div>

          <div
            className="flex justify-center cursor-pointer"
            onClick={() => {
              onSetCollapse?.(true);
            }}
          >
            <SvgIcon name="icon-shouzhe" />
          </div>
        </div>
      </div>
      {collapse && (
        <div
          onClick={() => {
            onSetCollapse?.(false);
          }}
          className="absolute bottom-[20px] left-[20px] z-[1] w-[40px] h-[40px] bg-white shadow-sm rounded-[50%] flex flex-row justify-center items-center cursor-pointer hover:bg-[#dde9ff] hover:text-[#2c79f1]"
        >
          <SvgIcon className="rotate-180" name="icon-shouzhe" />
        </div>
      )}
    </>
  );
}
